package com.example.browser;





import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import android.text.Editable;

import android.text.TextWatcher;

import android.view.MotionEvent;
import android.view.View;

import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;

import android.widget.EditText;

import android.widget.ListView;
import android.widget.SimpleAdapter;

import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by dhs on 2018/7/27.
 */

public class yad extends Activity {
    private ListView lv,folder_list;
    private MyDatabaseHelper dbHelper;



    private static final String FILENAME="YX";
    private String get_title,get_url,get_adtable;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private String titler, url;//按值查找详细信息
    int id; //按值查找id
    private ArrayList arrayList=new ArrayList();
    private boolean if_exist;

    public static yad instance = null;
    private static final String TABLENAME = "adDB";


    private EditText search_bookmark;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yad);
        instance = this;

        lv=(ListView)findViewById(R.id.bookmark_list);


        search_bookmark=(EditText)findViewById(R.id.search_ad) ;
        //监听编辑框
        search_bookmark.addTextChangedListener(new EditChangedListener());
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();

        queryinfo();

        onclick();


    }
    public void insert() {

    }
    private void onclick() {

        //点击函数：
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {
                    Intent intent = new Intent(yad.this,idclass.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("idclass", query_by_id(position));
                    startActivity(intent);
                }
            }
        });
        //长按选择删除
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_exist)
                    new AlertDialog.Builder(yad.this)
                            .setItems(new String[]{"删除该标识"}, (dialog, which) -> {
                                switch (which) {
                                    case 0:
                                        delete(position);
                                        break;
                                }
                            })
                            .show();

                return true;
            }
        });
    }












    public String adquery_by_id2(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from adDB", null);
        while (cursor.moveToNext()) {
            url=cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }
    //bookmarkDB删除函数：
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="drop table if exists "+adquery_by_id2(position);
        db.execSQL(sql);
        db.delete("adDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        queryinfo();


    }

    //全部删除
    public void delete_all(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+TABLENAME, null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete(TABLENAME,"id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        //刷新UI
        queryinfo();


    }

    //bookmarkDB全部删除对话框
    public void delete_all_dialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //数据库逆序查询函数：
    public void queryinfo(){
        arrayList.clear();
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query(TABLENAME, null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_adtable = cursor.getString(1);
                get_title = cursor.getString(2);
                get_url = cursor.getString(3);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"title","url"},
                        new int[] {R.id.title,R.id.url});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "暂无");
            map.put("url", "暂无");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }
    //按值查找：
    public String query_by_id(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+TABLENAME, null);
        while (cursor.moveToNext()) {
            get_adtable=cursor.getString(1);
            url = cursor.getString(3);
            titler=cursor.getString(2);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return get_adtable;
    }

    //数据库逆序查询函数：
    public void queryinfo2( String url ){
        arrayList.clear();
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";

        String sql = "select * from "+TABLENAME+" where url like '%"+ url + "%'OR title like '%"+ url + "%'";
        Cursor cursor=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"来自"+"title","已屏蔽"+"url"+"域名"},
                        new int[] {R.id.title,R.id.url});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "没有找到");
            map.put("url", "");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }

    //监听编辑框--https://www.jb51.net/article/135392.htm
    //https://blog.csdn.net/ycwol/article/details/46594275
    class EditChangedListener implements TextWatcher {
        public void afterTextChanged(Editable arg0) {
// 文字改变后出发事件
            String content = search_bookmark.getText().toString();
            //若输入框内容为空按钮可点击，字体为蓝色
            if (!content.isEmpty()) {
                queryinfo2(search_bookmark.getText().toString());
            } else {
                queryinfo();

            }

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
// TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

        }
    };

    //获取返回搜索url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if(resultCode==1){

                // int resultid=Integer.parseInt(data.getStringExtra("move"));
                // deleteid(resultid);


            }
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //finish();点击窗口外部区域 弹窗消失
        //点击空白处关闭键盘
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            //刷新UI
            queryinfo();

            search_bookmark.setText("");
        }
        return true;
    }



    @Override
    protected void onRestart() {
        super.onRestart();
        //刷新UI
        queryinfo();

    }


}